<template>
  <div class="order-list-page">
    <!-- 头部 -->
    <div class="header">
      <div class="back" @click="$router.back()">
        <i class="iconfont icon-back"></i>
      </div>
      <div class="title">历史订单</div>
    </div>

    <!-- 订单列表 -->
    <div class="order-list" v-if="orderList.length > 0">
      <div class="order-item" v-for="item in orderList" :key="item.orderId">
        <!-- 商家信息 -->
        <div class="business-info">
          <img :src="item.business?.businessImg" :alt="item.business?.businessName">
          <div class="business-detail">
            <div class="business-name">{{ item.business?.businessName }}</div>
            <div class="order-time">{{ formatDate(item.orderDate) }}</div>
          </div>
          <div class="order-status" :class="{ paid: item.orderState === 1 }">
            {{ item.orderState === 1 ? '已支付' : '待支付' }}
          </div>
        </div>

        <!-- 订单详情 -->
        <div class="order-detail">
          <div class="food-list" v-if="item.orderDetailetList">
            <div class="food-item" v-for="food in item.orderDetailetList" :key="food.odId">
              <img :src="food.food?.foodImg" :alt="food.food?.foodName">
              <div class="food-info">
                <div class="food-name">{{ food.food?.foodName }}</div>
                <div class="food-price">
                  <span class="price">￥{{ food.food?.foodPrice }}</span>
                  <span class="quantity">x{{ food.quantity }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="order-summary">
            <div class="total-info">
              <span>共{{ getTotalQuantity(item) }}件商品</span>
              <span class="total-price">实付 ￥{{ item.orderTotal }}</span>
            </div>
            <div class="action-buttons">
              <template v-if="item.orderState === 0">
                <div class="btn primary" @click="goToPay(item.orderId)">去支付</div>
                <div class="btn outline" @click="cancelOrder(item.orderId)">取消订单</div>
              </template>
              <template v-else>
                <div class="btn primary" @click="reorder(item)">再来一单</div>
                <div class="btn danger" @click="deleteOrder(item.orderId)">删除订单</div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-else>
      <i class="iconfont icon-order"></i>
      <p>暂无订单记录</p>
      <div class="go-shop" @click="$router.push('/')">去逛逛</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const orderList = ref([])
const userId = localStorage.getItem('userId')

// 获取订单列表
const getOrderList = async () => {
  try {
    const res = await axios.get('/orders/listOrdersByUserId', {
      params: { userId }
    })
    orderList.value = res.data
  } catch (error) {
    console.error('获取订单列表失败:', error)
  }
}

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(Number(timestamp))
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 去支付
const goToPay = (orderId) => {
  router.push({
    path: '/payment',
    query: { orderId }
  })
}

// 取消订单
const cancelOrder = async (orderId) => {
  if (!confirm('确定要取消此订单吗？')) return
  
  try {
    await axios.post('/orders/removeOrder', null, {
      params: { orderId }
    })
    getOrderList() // 重新获取订单列表
  } catch (error) {
    console.error('取消订单失败:', error)
    alert('取消订单失败，请重试')
  }
}

// 删除订单
const deleteOrder = async (orderId) => {
  if (!confirm('确定要删除此订单吗？')) return
  
  try {
    await axios.post('/orders/deleteOrder', null, {
      params: { orderId }
    })
    getOrderList() // 重新获取订单列表
  } catch (error) {
    console.error('删除订单失败:', error)
    alert('删除订单失败，请重试')
  }
}

// 再来一单
const reorder = async (order) => {
  try {
    // 先跳转到商家页面
    await router.push({
      path: `/business/${order.businessId}`
    })

    // 获取订单明细并添加到购物车
    if (order.orderDetailetList) {
      for (const item of order.orderDetailetList) {
        // 添加到购物车
        await axios.post('/cart/saveCart', null, {
          params: {
            userId,
            businessId: order.businessId,
            foodId: item.foodId
          }
        })
        
        // 如果数量大于1，更新购物车数量
        if (item.quantity > 1) {
          await axios.post('/cart/updateCart', null, {
            params: {
              userId,
              businessId: order.businessId,
              foodId: item.foodId,
              quantity: item.quantity
            }
          })
        }
      }
      // 添加成功提示
      alert('已添加到购物车')
    }
  } catch (error) {
    console.error('再来一单失败:', error)
    alert('添加购物车失败，请重试')
  }
}

const getTotalQuantity = (order) => {
  return order.orderDetailetList?.reduce((total, item) => total + item.quantity, 0) || 0
}

onMounted(() => {
  if (!userId) {
    router.push('/login')
    return
  }
  getOrderList()
})
</script>

<style scoped>
.order-list-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 44px 0 20px;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background: #0097ff;
  color: #fff;
  display: flex;
  align-items: center;
  padding: 0 15px;
  z-index: 100;
}

.back {
  padding: 10px;
  margin-left: -10px;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: 500;
}

.order-item {
  margin: 12px;
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.business-info {
  padding: 15px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
}

.business-info img {
  width: 45px;
  height: 45px;
  border-radius: 8px;
  margin-right: 12px;
  object-fit: cover;
}

.business-detail {
  flex: 1;
}

.business-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 4px;
  color: #333;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.order-status {
  font-size: 13px;
  color: #ff6b01;
  font-weight: 500;
}

.order-status.paid {
  color: #52c41a;
}

.order-detail {
  padding: 15px;
}

.food-list {
  margin-bottom: 15px;
}

.food-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.food-item:last-child {
  margin-bottom: 0;
}

.food-item img {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  margin-right: 10px;
  object-fit: cover;
}

.food-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.food-name {
  font-size: 14px;
  color: #333;
}

.food-price {
  text-align: right;
}

.price {
  font-size: 14px;
  color: #ff6b01;
  margin-right: 8px;
}

.quantity {
  font-size: 12px;
  color: #999;
}

.order-summary {
  padding-top: 15px;
  border-top: 1px solid #f5f5f5;
}

.total-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 13px;
  color: #666;
}

.total-price {
  font-size: 15px;
  font-weight: 500;
  color: #ff6b01;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn {
  padding: 6px 12px;
  border-radius: 15px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn.primary {
  background: #0097ff;
  color: #fff;
}

.btn.outline {
  border: 1px solid #ddd;
  color: #666;
}

.btn.danger {
  border: 1px solid #ff4d4f;
  color: #ff4d4f;
}

.btn:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.empty-state {
  padding-top: 120px;
  text-align: center;
  color: #999;
}

.empty-state i {
  font-size: 60px;
  margin-bottom: 15px;
}

.empty-state p {
  font-size: 14px;
  margin-bottom: 20px;
}

.go-shop {
  display: inline-block;
  padding: 8px 24px;
  background: #0097ff;
  color: #fff;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
}

.go-shop:active {
  opacity: 0.9;
}
</style>